package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result find(Long id) {
        //查询笔记
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        //设置name，icon
        queryBlogUser(blog);
        //查询笔记是否被点赞
        isLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result pageFind(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户并设置相关属性
        records.forEach(
                blog -> {
                    this.queryBlogUser(blog);
                    this.isLiked(blog);
                }
        );
        return Result.ok(records);
    }


    private void isLiked(Blog blog) {
        //1.获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return;
        }
        Long id = user.getId();
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, id.toString());
        blog.setIsLike(score != null);
    }

    @Override
    public Result likeBlog(Long id) {
        //思路：一个用户只能点赞一次，再次点击就是取消点赞
        //1.查询redis，是否点赞过
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        //在set里面返回true,不在返回true
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null) {
            //表示没点赞
            //1.数据库点赞数+1
            boolean success = update().setSql("liked=liked+1").eq("id", id).update();
            if (success) {
                //写入redis
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //表示点赞过了，如果再点就取消点赞
            boolean success1 = update().setSql("liked=liked-1").eq("id", id).update();
            if (success1) {
                //删除redis中的数据
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }


    @Override
    public Result queryBlogLikes(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        //0-5包头不包尾
        Set<String> UserIdSet = stringRedisTemplate.opsForZSet().range(key, 0, 5);
        //判断
        if (UserIdSet == null || UserIdSet.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //已经拿到UserId集合
        //但是我们需要拿到User集合，再转为UserDto

        //1.解析出id去查询用户得到User
        List<Long> ids = UserIdSet.stream().map(Long::valueOf).collect(Collectors.toList());
        //2.根据ids查询用户
        String s = StrUtil.join(",", ids);
        List<User> user = userService.query().in("id", ids).last("order by field (id," + s + ")").list();
        List<UserDTO> userDTOS = user.stream().map(user1 -> BeanUtil.copyProperties(user1, UserDTO.class)).collect(Collectors.toList());

        //返回UserDto集合对象（三个参数）
        return Result.ok(userDTOS);
    }


    //实现分页查询收邮箱
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1.查询收件箱
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);

        //2.非空判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }

        //3.解析数据，得到blogId，min(时间戳)、offset
        List<Long> list = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //获取blogId
            list.add(Long.valueOf(typedTuple.getValue()));
            //获取时间戳
            long time = typedTuple.getScore().longValue();
            //例如 5 4 4 2 2
            if (minTime == time) {
                os++;
            } else {
                minTime = time;
                os = 1;
            }
        }
        //4.根据id查询blog
        String idStr = StrUtil.join(",", list);
        List<Blog> blogs = query().in("id", list).last("ORDER BY FIELD(id," + idStr + ")").list();
        //5.blog还要去查询相关用户和是否被点赞
        blogs.forEach(
                blog -> {
                    this.queryBlogUser(blog);
                    this.isLiked(blog);
                }
        );

        //6.封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(os);
        return Result.ok(scrollResult);
    }


    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

}
